<?php

namespace app\admin\model\merchant;

use app\admin\model\admin\Admin;
use app\admin\validate\merchant\Merchant;
use think\exception\ValidateException;
use think\Model;
use ulit\CryptAES;

class MerchantModel extends Model
{

    protected  $autoWriteTimestamp = 'datetime';

    protected $createTime = 'create_time';

    protected $updateTime = 'update_time';

    protected $table = 'pay_merchant';

    protected $json=['ip'];


    protected $jsonAssoc=true;
    public function getIpAttr($value)
    {

        return    implode(',',$value);


    }

    public static function add(){

        try {
            $add=input('');
            $role_info=session('role_info');

            $result = validate(Merchant::class)->check($add);
            if(!empty($result)){
                $add['admin_id']=session('admin_id');
                $add['ip']=!empty($add['ip'])?explode(',', $add['ip']):'{}';;

                $result=self::create($add);
                $data = array(
                    'code' => 200,
                    'msg' => '成功!',
                );

                return $data;
                // dump($result);die;
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $e->getError();
        }
    }

    public static function edit($id){
        try {
            $add=input('');
            $result = validate(Merchant::class)->scene('Modify')->check($add);
            if(!empty($result)){
                $add['ip']=!empty($add['ip'])?explode(',', $add['ip']):'{}';
                self::where(['id'=>$id])->save($add);
                $data = array(
                    'code' => 200,
                    'msg' => '成功!',
                );

                return $data;
                // dump($result);die;
            }
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return $e->getError();
        }
    }
    public function GetAdminInfo(){

        return $this->hasOne(Admin::class,'id','admin_id')->field(['username','rate','id'])->bind(['rate','username']);

    }
    public static function merchantList(){

        $role_info=session('role_info');
        $where=[];
        $role_info['type']!=1 && $where['admin_id']=session('admin_id');
        $result=self::where($where)->with(['GetAdminInfo'])->select();

            return $result;

    }

    public static function merchantInfo($id,$type='admin'){

        $type=='admin' && $where['admin_id']=$id;
        $type!='admin' && $where['id']=$id;
        self::where($where)->find();
    }

}